package gsw.tool.eventbus.core;

import android.text.TextUtils;

import com.google.gson.Gson;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import gsw.tool.eventbus.response.Response;
import gsw.tool.eventbus.response.ResponceBean;
import gsw.tool.eventbus.service.HermesService;

/**
 * Hermes的代理
 */
public class HermesInvocationHandler implements InvocationHandler {

    private static final Gson GSON = new Gson();
    private static final String TAG = "david";
    private Class clazz;
    private Class hermeService;

    public HermesInvocationHandler(Class<? extends HermesService> service, Class clazz) {
        this.clazz = clazz;
        this.hermeService = service;
    }

    /**
     * 代理服务端的对象，通过发送Request实现
     *
     * @param proxy  原始对象
     * @param method 代理方法
     * @param args   方法参数
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //通过Binder对象发送请求
        Response response = Hermes.getDefault().sendObjectRequest(hermeService, clazz, method, args);
        //解析Responce，得到实际的返回结果
        if (!TextUtils.isEmpty(response.getData())) {
            ResponceBean responceBean = GSON.fromJson(response.getData(), ResponceBean.class);
            if (responceBean.getData() != null) {
                Object getUserReslut = responceBean.getData();
                String data = GSON.toJson(getUserReslut);
                Class stringgetUser = method.getReturnType();
                Object o = GSON.fromJson(data, stringgetUser);
                return o;
            }
        }
        return null;
    }
}
